# -*- coding: utf-8 -*-
from paho.mqtt import client as mqtt
import time
import json

from Ini_utils import UtilIni
from utils.logging_util import Log


class MqttClient:
    @staticmethod
    def dclient(topic, payload):
        """
        fat模式发送mqtt报文
        :param topic: 报文头
        :param payload: 报文内容
        :return:
        """
        try:
            dmqttClient = mqtt.Client(protocol=3)
            dmqttClient.username_pw_set(UtilIni().getvalue("DEV", "name"),
                                        UtilIni().getvalue("DEV", "pwd"))  # mqtt服务器账号密码
            dmqttClient.connect(host=UtilIni().getvalue("DEV", "ip"), port=int(UtilIni().getvalue("DEV", "port")),
                                keepalive=60)
            time.sleep(1)
            dmqttClient.publish(topic=topic, payload=json.dumps(payload, ensure_ascii=False), qos=2)
        except Exception as e:
            Log().error(f"mqtt连接失败，请检查VPN是否开启...错误：{e}")

    @staticmethod
    def fclient(topic, payload):
        """
        fat模式发送mqtt报文
        :param topic: 报文头
        :param payload: 报文内容
        :return:
        """
        try:
            fmqttClient = mqtt.Client(protocol=3)
            fmqttClient.username_pw_set(UtilIni().getvalue("FAT", "name"),
                                        UtilIni().getvalue("FAT", "pwd"))  # mqtt服务器账号密码
            fmqttClient.connect(host=UtilIni().getvalue("FAT", "ip"), port=int(UtilIni().getvalue("FAT", "port")),
                                keepalive=60)
            time.sleep(1)
            fmqttClient.publish(topic=topic, payload=json.dumps(payload, ensure_ascii=False), qos=2)
        except Exception as e:
            Log().error(f"mqtt连接失败，请检查VPN是否开启...错误：{e}")

    @staticmethod
    def uclient(topic, payload):
        """
        uat环境发送mqtt报文内容
        :param topic:
        :param payload:
        :return:
        """
        try:
            umqttClient = mqtt.Client(protocol=3)
            umqttClient.username_pw_set("admin", "veZgHjmY")  # mqtt服务器账号密码
            umqttClient.connect(host='10.4.6.74', port=12883,
                                keepalive=60)
            time.sleep(1)
            umqttClient.publish(topic=topic, payload=json.dumps(payload, ensure_ascii=False), qos=2)

        except Exception as e:
            Log().error(f"mqtt连接失败，请检查VPN是否开启...错误：{e}")